import { readFile, writeFile, readdirSync } from "fs";
import * as uglify from 'uglify-es';
import { extname, join, dirname } from "path";
import { createDirSync } from "./FileUtil";

export function compressDirJs(fromDir: string, toDir: string, callback: Function, logFunc?: (msg: string) => void, es6Toes5: boolean = false) {
    let files = readdirSync(fromDir);
    let jsList = [];
    for (let i = 0; i < files.length; i++) {
        if (extname(files[i]) == ".js") {
            jsList.push(files[i]);
        }
    }
    function compressNext() {
        if (jsList.length > 0) {
            let jsFileName = jsList.shift();
            compressJs(join(fromDir, jsFileName), join(toDir, jsFileName), (isSuccess: boolean) => {
                compressNext();
                logFunc && logFunc(jsFileName + "压缩" + (isSuccess ? "成功" : "失败"));
            }, es6Toes5)
        } else {
            callback && callback();
        }
    }
    compressNext();
}

export function compressJs(fromPath: string, toPath: string, callback: Function, es6Toes5: boolean = false) {
    let startT = Date.now();
    readFile(fromPath, (err, data: Buffer) => {
        if (err) {
            console.log("文件读取失败--", err);
            callback && callback(false);
        } else {
            let rst = uglify.minify(data.toString(), {
                mangle: true
            });
            createDirSync(dirname(toPath));
            if (!rst.code) {
                console.warn('压缩失败:' + rst.error);
                callback && callback(false);
            }
            writeFile(toPath, rst.code, (err: any) => {
                if (err) {
                    console.warn('写入压缩文件失败:' + toPath);
                } else {
                    console.log(`压缩[${toPath}]完成，耗时(${Date.now() - startT}毫秒)`);
                }
                callback && callback(true);
            });
        }
    })
}

export function compressJsAsync(fromPath: string, toPath: string, es6Toes5: boolean = false) {
    return new Promise((resolve, reject) => {
        compressJs(fromPath, toPath, (success) => {
            resolve(success);
        }, es6Toes5);
    })
}